package com.example.content_android.me;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.content_android.MainActivity;
import com.example.content_android.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

import jp.wasabeef.richeditor.RichEditor;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MessageMeActivity extends AppCompatActivity {

    private EditText messageTitle=null;

    private EditText messageAddress=null;

    private EditText messageCaptcha=null;

    private ImageView messageCaptchaImage=null;

    private RichEditor messageContent=null;
    private TextView mPreview;

    private static String uuidStr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //隐藏界面默认标题栏
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        //设置顶部状态栏黑底白字（最上面这一行显示电池、时钟、wifi等图标是状态栏）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.BLACK);
        }
        setContentView(R.layout.activity_message_me);
        getData();

        try {
            getCaptcha();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String generateUUID()
    {
        UUID uuid = UUID.randomUUID();
        System.out.println(uuid.toString());
        uuidStr=uuid.toString();
        return uuidStr;
    }

    public void getData() {
        messageTitle = findViewById(R.id.messageTitle);
        messageAddress = findViewById(R.id.messageAddress);
        messageCaptcha = findViewById(R.id.messageCaptcha);
        messageCaptchaImage = findViewById(R.id.messageCaptchaImage);
        messageContent = findViewById(R.id.messageContent);
        //初始化编辑高度
        messageContent.setEditorHeight(200);
        //初始化字体大小
        messageContent.setEditorFontSize(22);
        //初始化字体颜色
        messageContent.setEditorFontColor(Color.BLACK);
        //mEditor.setEditorBackgroundColor(Color.BLUE);

        //初始化内边距
        messageContent.setPadding(10, 10, 10, 10);
        //设置编辑框背景，可以是网络图片
        // mEditor.setBackground("https://raw.githubusercontent.com/wasabeef/art/master/chip.jpg");
//        messageContent.setBackgroundColor(Color.BLUE);
        messageContent.setBackgroundResource(R.drawable.bg);
        //设置默认显示语句
        messageContent.setPlaceholder("Insert text here...");
        //设置编辑器是否可用
        messageContent.setInputEnabled(true);

//        mPreview = (TextView) findViewById(R.id.preview);
//        messageContent.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
//            @Override public void onTextChange(String text) {
//                mPreview.setText(text);
//            }
//        });

        findViewById(R.id.action_undo).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.undo();
            }
        });

        findViewById(R.id.action_redo).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.redo();
            }
        });

        findViewById(R.id.action_bold).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setBold();
            }
        });

        findViewById(R.id.action_italic).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setItalic();
            }
        });

        findViewById(R.id.action_subscript).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setSubscript();
            }
        });

        findViewById(R.id.action_superscript).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setSuperscript();
            }
        });

        findViewById(R.id.action_strikethrough).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setStrikeThrough();
            }
        });

        findViewById(R.id.action_underline).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setUnderline();
            }
        });

        findViewById(R.id.action_heading1).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setHeading(1);
            }
        });

        findViewById(R.id.action_heading2).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setHeading(2);
            }
        });

        findViewById(R.id.action_heading3).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setHeading(3);
            }
        });

        findViewById(R.id.action_heading4).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setHeading(4);
            }
        });

        findViewById(R.id.action_heading5).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setHeading(5);
            }
        });

        findViewById(R.id.action_heading6).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setHeading(6);
            }
        });

        findViewById(R.id.action_txt_color).setOnClickListener(new View.OnClickListener() {
            private boolean isChanged;

            @Override public void onClick(View v) {
                messageContent.setTextColor(isChanged ? Color.BLACK : Color.RED);
                isChanged = !isChanged;
            }
        });

        findViewById(R.id.action_bg_color).setOnClickListener(new View.OnClickListener() {
            private boolean isChanged;

            @Override public void onClick(View v) {
                messageContent.setTextBackgroundColor(isChanged ? Color.TRANSPARENT : Color.YELLOW);
                isChanged = !isChanged;
            }
        });

        findViewById(R.id.action_indent).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setIndent();
            }
        });

        findViewById(R.id.action_outdent).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setOutdent();
            }
        });

        findViewById(R.id.action_align_left).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setAlignLeft();
            }
        });

        findViewById(R.id.action_align_center).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setAlignCenter();
            }
        });

        findViewById(R.id.action_align_right).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setAlignRight();
            }
        });

        findViewById(R.id.action_blockquote).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.setBlockquote();
            }
        });

        findViewById(R.id.action_insert_image).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.insertImage("http://www.1honeywan.com/dachshund/image/7.21/7.21_3_thumb.JPG",
                        "dachshund");
            }
        });

        findViewById(R.id.action_insert_link).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.insertLink("https://github.com/wasabeef", "wasabeef");
            }
        });
        findViewById(R.id.action_insert_checkbox).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                messageContent.insertTodo();
            }
        });


    }

    public void getCaptcha() throws IOException {

        Response response = OkHttpUtils
                .get()//
                .url("https://www.turkeylike.cn:8900/fzulab/messagebook/captcha.jpg")//
                .addParams("uuid", generateUUID())
                .tag(this)//
                .build()//
                .execute();

        InputStream inputStream = response.body().byteStream();
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        messageCaptchaImage.setImageBitmap(bitmap);

    }
    final static Pattern partern = Pattern.compile("[a-zA-Z0-9]+[\\.]{0,1}[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z]+");
    /**
     * 验证输入的邮箱格式是否符合
     * @param email
     * @return 是否合法
     */
    public static boolean emailFormat(String email){
        boolean isMatch = partern.matcher(email).matches();
        return isMatch;
    }



    public void messageMe(View v) {
        String title = messageTitle.getText().toString();
        String address = messageAddress.getText().toString();
        String captcha = messageCaptcha.getText().toString();
        if (TextUtils.isEmpty(title))//判断标题是否为空
        {
            Toast.makeText(this, "标题为空！", Toast.LENGTH_SHORT).show();

            return;
        }
        if (TextUtils.isEmpty(address)) {
            Toast.makeText(this, "地址为空！", Toast.LENGTH_SHORT).show();

            return;
        }else{
            if(!emailFormat(address)){
                Toast.makeText(this, "请输入正确邮箱地址！", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (TextUtils.isEmpty(captcha)) {
            Toast.makeText(this, "验证码为空！", Toast.LENGTH_SHORT).show();

            return;
        }

        String content=messageContent.getHtml();

        MediaType JSONType = MediaType.parse("application/json; charset=utf-8");
        JSONObject json = new JSONObject();


        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);

        String token = sp.getString("token","");


        try {
            json.put("title", title);
            json.put("content", content);
            json.put("email", address);
            json.put("uuid", uuidStr);
            json.put("captcha", captcha);

        } catch (JSONException e) {
            e.printStackTrace();
        }


        OkHttpUtils
                .postString()
                .url("https://www.turkeylike.cn:8900/fzulab/messagebook/save")
                .content(json.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(
                        new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Log.e("onResponse", "response");
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                JSONObject responseStr = JSON.parseObject(response);
                                if( responseStr.getInteger("code")==500){
                                    String msg=responseStr.getString("msg");

                                    Toast.makeText(getBaseContext(),msg,Toast.LENGTH_SHORT).show();
                                    return;

                                }
                                if( responseStr.getInteger("code")==0){
                                    String msg=responseStr.getString("msg");

                                    Toast.makeText(getBaseContext(),"新增留言成功！",Toast.LENGTH_SHORT).show();

                                    messageTitle.setText("");
                                    messageAddress.setText("");
                                    messageCaptcha.setText("");
                                    try {
                                        getCaptcha();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    messageContent.setHtml("");


                                }
                                Log.e("onResponse", "response");
                            }

                        });



    }

}
